package com.example.lenovo.asia5b.my.fragment;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.ListView;
import android.widget.TextView;

import com.example.lenovo.asia5b.my.adapter.MyDaikinRollTwoAdapter;
import com.example.lenovo.asia5b.my.bean.MyDaikinRollBean;
import com.example.lenovo.asia5b.ui.LoadingDalog;
import com.example.lenovo.asia5b.ui.PullToRefreshLayout;
import com.example.lenovo.asia5b.util.ICallBack;
import com.example.lenovo.asia5b.util.JsonTools;
import com.example.lenovo.asia5b.util.Logic;
import com.example.lenovo.asia5b.util.MD5;
import com.example.lenovo.asia5b.util.Setting;
import com.wushi.lenovo.asia5b.R;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import app.BaseFragment;
import fay.frame.ui.U;

import static com.example.lenovo.asia5b.util.SharedPreferencesUtils.getUserBean;


/**
 * 我的代金券
 * Created by lenovo on 2017/6/22.
 */

public class MyDaikinRollFragment extends BaseFragment implements ICallBack, PullToRefreshLayout.OnRefreshListener {
    public View fragmentView;
    private ListView lv_my_daikin_roll;
    private MyDaikinRollTwoAdapter adapter;
    private PullToRefreshLayout pullToRefreshLayout;
    private int page  = 1;
    private int countPage = 0;
    private LoadingDalog loadingDalog;
    private List<MyDaikinRollBean> lists ;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        fragmentView = inflater.inflate(R.layout.frame_my_daikin_roll, container,
                false);

        initView();
        MyDaikinRollData();
        return fragmentView;
    }

    public void initView() {
        loadingDalog = new LoadingDalog(getActivity());
        loadingDalog.show();
        lv_my_daikin_roll = (ListView)fragmentView.findViewById(R.id.lv_my_daikin_roll);
        adapter = new MyDaikinRollTwoAdapter(getActivity());
        lv_my_daikin_roll.setAdapter(adapter);
        pullToRefreshLayout = ((PullToRefreshLayout)fragmentView.findViewById(R.id.refresh_view));
        pullToRefreshLayout.setOnRefreshListener(this);
        lv_my_daikin_roll.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScroll(AbsListView arg0, int arg1, int arg2, int arg3) {
            }

            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {
                // 当不滚动时
                if (scrollState == AbsListView.OnScrollListener.SCROLL_STATE_IDLE) {
                    // 判断是否滚动到底部
                    if (view.getLastVisiblePosition() == view.getCount() - 1) {
                        if (page < countPage) {
                            page += 1;
                            MyDaikinRollData();
                        } else {
                            TextView load_tv = (TextView)fragmentView.findViewById(R.id.load_tv);
                            load_tv.setText(getResources().getString(R.string.no_more_data));
                            load_tv.setVisibility(View.VISIBLE);
                        }
                    }
                }
            }
        });

    }

    private Handler handler2 = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            JSONObject result= null;
            try {
                result = new JSONObject(msg.obj.toString());
            } catch (Exception e) {
            }
            int action = msg.what;
            if (action == 0) {
                if (null != result && result instanceof JSONObject) {
                    try {
                        JSONObject json =  (JSONObject)result;
                        int state = (int)json.getInt("State");
                        if (state == 0) {
                            JSONObject paging = json.getJSONObject("paging");
                            if (null!=paging.getString("page") && "1".equals(paging.getString("page"))) {
                                initPaging(paging);
                                JSONArray bonus = json.getJSONArray("bonus");
                                lists = Logic.getListToBean(bonus,new MyDaikinRollBean());
                                adapter.setLists(lists);
                                adapter.notifyDataSetChanged();

                            } else if(null!=paging.getString("page") && !"1".equals(paging.getString("page"))){
                                JSONArray bonus = (JSONArray) json.get("bonus");
                                if (null != bonus && bonus.length() > 0) {
                                    List<MyDaikinRollBean> listBean  =  Logic.getListToBean(bonus,new MyDaikinRollBean());
                                    for (int i = 0; i < listBean.size(); i++) {
                                        lists .add(listBean.get(i));
                                    }
                                    adapter .setLists(lists);
                                    adapter .notifyDataSetChanged();
                                } else {
                                    page = page - 1;
                                }

                            }

                        }  else if (state == 1) {
                            U.Toast(getActivity(), getResources().getString(R.string.qmsb));
                        } else if (state == 2) {
                            U.Toast(getActivity(), getResources().getString(R.string.cscw));
                        }
                    } catch (Exception e) {
                    }
                }
                loadingDalog.dismiss();
                pullToRefreshLayout.refreshFinish(PullToRefreshLayout.SUCCEED);
                pullToRefreshLayout.loadmoreFinish(PullToRefreshLayout.SUCCEED);
            }
        }
    };


    @Override
    public void logicFinish(Object result, int action) {
        Message msg = new Message();
        msg.what = action;
        msg.obj = result.toString();
        handler2.sendMessage(msg);
    }

    /**
     * 向下刷新
     */
    @Override
    public void onRefresh(PullToRefreshLayout pullToRefreshLayout) {
        loadingDalog.show();
        page = 1;
        MyDaikinRollData();
    }

    /**
     * 向上加载
     */
    @Override
    public void onLoadMore(PullToRefreshLayout pullToRefreshLayout) {
        pullToRefreshLayout.loadmoreFinish(PullToRefreshLayout.SUCCEED);
    }


    /**
     * 我的代金券接口
     */
    public void MyDaikinRollData() {
        try {
            Map<String, String> parmaMap = new HashMap<String, String>();
            String url = Setting.VOUCHER;
            String user_id = getUserBean().user_id;
            Date date = new Date();
            String time = String.valueOf(date.getTime());
            String[] sort = {"user_id"+user_id,"page"+page,"time"+time};
            String sortStr = Logic.sortToString(sort);
            String md5_32 = MD5.MD5EncryptionFor32(MD5.MD5EncryptionFor32(sortStr));//二次加密
            parmaMap.put("user_id", user_id);
            parmaMap.put("page",""+page);
            parmaMap.put("time",time);
            parmaMap.put("sign",md5_32);
            JsonTools.getJsonAll(this, url, parmaMap, 0);
        }catch (Exception e) {

        }
    }

    public void initPaging(JSONObject json) throws JSONException {
        String pageSizeString = json.getString("count");
        String countPageString = json.getString("countpage");
        String pageString = json.getString("page");
        if (pageSizeString != null && countPageString != null && pageString != null) {
            countPage = Integer.parseInt(countPageString);
            if (countPage <=1) {
                pullToRefreshLayout.stopLoadMore();
            }
        }
    }

}